"""用户管理模块序列化器"""
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework.validators import UniqueValidator

class UserListSerializer(serializers.ModelSerializer):
    """用户列表序列化器"""
    full_name = serializers.SerializerMethodField(help_text="全名")
    status = serializers.SerializerMethodField(help_text="状态")
    
    class Meta:
        model = User
        fields = '__all__'  # 🔑 关键：统一使用 '__all__'
        read_only_fields = ['id', 'date_joined', 'last_login', 'groups', 'user_permissions']

    def get_full_name(self, obj) -> str:
        """获取全名"""
        return f"{obj.last_name}{obj.first_name}" if obj.last_name and obj.first_name else obj.username

    def get_status(self, obj) -> str:
        """获取用户状态"""
        if not obj.is_active:
            return "已禁用"
        elif obj.is_staff:
            return "管理员"
        else:
            return "普通用户"

class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化器"""
    full_name = serializers.SerializerMethodField(help_text="全名")
    status = serializers.SerializerMethodField(help_text="状态")

    # 🔑 关键：重写groups和user_permissions字段，返回ID列表而不是字符串列表
    groups = serializers.SerializerMethodField(help_text="用户组ID列表")
    user_permissions = serializers.SerializerMethodField(help_text="用户权限ID列表")

    # 额外提供名称列表用于显示
    group_names = serializers.SerializerMethodField(help_text="用户组名称列表")
    permission_names = serializers.SerializerMethodField(help_text="用户权限名称列表")
    
    class Meta:
        model = User
        fields = '__all__'  # 🔑 关键：统一使用 '__all__'
        read_only_fields = ['id', 'username', 'date_joined', 'last_login', 'groups', 'user_permissions']

    def get_full_name(self, obj) -> str:
        """获取全名"""
        return f"{obj.last_name}{obj.first_name}" if obj.last_name and obj.first_name else obj.username

    def get_status(self, obj) -> str:
        """获取用户状态"""
        if not obj.is_active:
            return "已禁用"
        elif obj.is_superuser:
            return "超级管理员"
        elif obj.is_staff:
            return "管理员"
        else:
            return "普通用户"

    def get_groups(self, obj) -> list[int]:
        """获取用户组ID列表"""
        return list(obj.groups.values_list('id', flat=True))

    def get_user_permissions(self, obj) -> list[int]:
        """获取用户权限ID列表"""
        return list(obj.user_permissions.values_list('id', flat=True))

    def get_group_names(self, obj) -> list[str]:
        """获取用户组名称列表"""
        return list(obj.groups.values_list('name', flat=True))

    def get_permission_names(self, obj) -> list[str]:
        """获取用户权限名称列表"""
        return list(obj.user_permissions.values_list('name', flat=True))

class UserCreateSerializer(serializers.ModelSerializer):
    """用户创建序列化器"""
    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=User.objects.all(), message="该邮箱已被注册")]
    )
    password = serializers.CharField(
        write_only=True,
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'},
        help_text="密码长度至少8位，不能是常见密码"
    )
    first_name = serializers.CharField(required=True, help_text="名字")
    last_name = serializers.CharField(required=True, help_text="姓氏")

    class Meta:
        model = User
        fields = '__all__'  # 🔑 关键：统一使用 '__all__'
        read_only_fields = ['id', 'date_joined', 'last_login', 'groups', 'user_permissions']
        extra_kwargs = {
            'username': {
                'validators': [UniqueValidator(queryset=User.objects.all(), message="该用户名已被使用")]
            },
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        """创建用户"""
        password = validated_data.pop('password')
        user = User.objects.create_user(**validated_data)
        user.set_password(password)
        user.save()
        return user

class UserUpdateSerializer(serializers.ModelSerializer):
    """用户更新序列化器"""
    email = serializers.EmailField(required=False)

    class Meta:
        model = User
        fields = '__all__'  # 🔑 关键：统一使用 '__all__'
        read_only_fields = ['id', 'username', 'date_joined', 'last_login']

    def validate_email(self, value):
        """验证邮箱唯一性"""
        if value and User.objects.filter(email=value).exclude(id=self.instance.id).exists():
            raise serializers.ValidationError("该邮箱已被其他用户使用")
        return value

class UserStatusSerializer(serializers.Serializer):
    """用户状态操作序列化器"""
    is_active = serializers.BooleanField(help_text="是否激活")
    reason = serializers.CharField(required=False, help_text="操作原因")

class UserPasswordResetSerializer(serializers.Serializer):
    """管理员重置用户密码序列化器"""
    new_password = serializers.CharField(
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'},
        help_text="新密码"
    )
    reason = serializers.CharField(required=False, help_text="重置原因")

class BulkDeleteSerializer(serializers.Serializer):
    """批量删除序列化器"""
    ids = serializers.ListField(
        child=serializers.IntegerField(),
        min_length=1,
        help_text="要删除的用户ID列表"
    )
    reason = serializers.CharField(required=False, help_text="删除原因")

class BulkDeleteResultSerializer(serializers.Serializer):
    """批量删除结果序列化器"""
    deleted_count = serializers.IntegerField(help_text="删除的用户数量")
    deleted_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="已删除的用户ID列表"
    )
